package com.opages.netty.demo.lesson.dark_horse3;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.Random;

/**
 * @author daizhong.liu
 * @create 2022-01-06 10:59
 **/
@Slf4j
public class StickyBagClient {
    static class SimpleInboundHandler extends ChannelInboundHandlerAdapter {
        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
            log.debug("sending...");
            // 每次发送16个字节的数据，共发送10次
//                                            for (int i = 0; i < 10; i++) {
//                                                ByteBuf buffer = ctx.alloc().buffer();
//                                                buffer.writeBytes(new byte[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15});
//                                                ctx.writeAndFlush(buffer);
//                                            }
            for (int i = 0; i < 10; i++) {
                ByteBuf buffer = ctx.alloc().buffer();
                byte len = (byte)(i + 97);
                buffer.writeBytes(new byte[]{len});
                ctx.writeAndFlush(buffer);
            }
        }
    }
    //定长16发送
    static class FixedLengthFrameInboundHandler extends ChannelInboundHandlerAdapter {
        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
            int maxLen = 16;
            char c = 'a';
            for(int i=0; i < 10; i++) {
                ByteBuf buf = ByteBufAllocator.DEFAULT.buffer(maxLen);
                byte[] bytes = new byte[maxLen];
                for(int j=0;j < (int)(Math.random() * (maxLen -1));j++) {
                    bytes[j] = (byte) c;
                }
                buf.writeBytes(bytes);
                ctx.writeAndFlush(buf);
                c++;
            }
        }
    }
    //按结束符
    static class DelimiterBasedInboundHandler extends ChannelInboundHandlerAdapter {
        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
            int maxLen = 64;
            char c = 'a';
            for(int i=0; i < 10; i++) {
                ByteBuf buf = ctx.alloc().buffer(maxLen);
                Random random = new Random();
                StringBuilder sb = new StringBuilder();
                for(int j=0;j < (random.nextInt(maxLen-6)+5);j++) {
                    sb.append(c);
                }
                sb.append("\n");
                log.debug("发送数据--->  {}",sb.toString());
                buf.writeBytes(sb.toString().getBytes(CharsetUtil.UTF_8));
                ctx.writeAndFlush(buf);
                c++;
            }
        }
    }

    public static void main(String[] args) {
        EventLoopGroup worker = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            ChannelFuture channelFuture = bootstrap.group(worker).channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline()
                                    .addLast(new LoggingHandler(LogLevel.DEBUG))
                                    .addLast(new DelimiterBasedInboundHandler());
                        }
                    }).connect("localhost", 8889).sync();
            channelFuture.channel().closeFuture().sync();
        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            worker.shutdownGracefully();
        }
    }
}
